local blaze = require "blaze"
local game = require "club.threecard.scibo"
local consts = game.util.consts
local sprite_type = typeof(CS.UnityEngine.Sprite).AssemblyQualifiedName

local M = game.ui.element()

M.store_watchers = {
    gameplay = {
        ["$"] = blaze.noop,

        ["展示结果"] = function(self, store, state, args, initialize)
            local n_1, n_2, n_3 = state.result_view.n_1, state.result_view.n_2, state.result_view.n_3
            self:result(n_1, n_2, n_3)
        end,
        ["阶段变更"] = function(self, store, state, args, initialize)
            if state.phase_id == consts.PHASE_IDLE then
                self.animator:Play("dice_close_clip")
            elseif state.phase_id == consts.PHASE_BET then
                self.animator:Play("dice_startbet_clip")
            elseif state.phase_id == consts.PHASE_REVEAL then
                self.animator:Play("dice_stopbet_clip")
            end
        end
    }
}

local cache_point = {}

local function get_sprite_sync(n)
    local random_pos = math.random(8)
    local sprite_name = string.format("%s_%s", n, random_pos)
    if cache_point[sprite_name] then
        return cache_point[sprite_name]
    end
    local res = string.format("club.threecard.scibo/atlases/ingame.b:%s:%s", sprite_name, sprite_type)
    local isOk, result = game.gamelib.res.load(res, {sync = true})

    cache_point[sprite_name] = result

    return result
end

function M:ctor()
    self.res = "club.threecard.scibo/ui/ingame.b:dice_shower"
end

local TIME = 0.7
function M:result(n_1, n_2, n_3)
    self.n_1.sprite = get_sprite_sync(n_1)
    self.n_2.sprite = get_sprite_sync(n_2)
    self.n_3.sprite = get_sprite_sync(n_3)

    self:start_coroutine(function()
        game.coroutine.wait(TIME)
        game.audio.post(string.format("scibo:%s", n_1))
        game.coroutine.wait(TIME)
        game.audio.post(string.format("scibo:%s", n_2))
        game.coroutine.wait(TIME)
        game.audio.post(string.format("scibo:%s", n_3))
    end)
end

return M